<template>
    <div>
      <cus-modal ref="modal" :title="this.form.id ? '编辑角色' : '添加角色'" @on-visible-change="onVisibleChange" @onOk="onOk">
        <Form ref="formValidate" :model="form" :rules="ruleValidate" :label-width="100">
        <FormItem label="角色名称" prop="name" :rules="{ required: true, message: '角色名称不能为空', trigger: 'blur' }">
          <Input v-model="form.name" maxlength="20" clearable style="width: 200px;" placeholder="请输入角色名称"></Input>
        </FormItem>
        <FormItem label="角色描述" prop="descr">
          <Input v-model="form.descr" maxlength="20" clearable style="width: 200px"></Input>
        </FormItem>
        <!-- <FormItem label="角色归属" prop="levelName" :rules="{ required: true, message: '角色不能为空', trigger: 'change' }">
          <Select class="multiple-select" clearable  v-model="form.levelName" style="width:200px" size="large" @on-change="changeLevel">
            <Option v-for="(item, ind) in unitLevelList" :value="item.levelName"  :key="item.id">{{ item.levelName }}
            </Option>
          </Select>
        </FormItem>
        <div style="width: 275px;" >
          <div  @click="radioChange()"><Radio  :value="form.isAdmin" label="管理员" ></Radio>
          </div>
        </div> -->
   
          <FormItem label="权限列表" prop="resourceIdList">
            <div class="permission hide-scrollbar">
              <roleTree ref="roleTree" v-if="!form.id  || form.resourceIdList.length"
                        @onOver="onOver"
                        @onReady="() => {this.loading = false}"
                        :resourceIdList.sync="form.resourceIdList"></roleTree>
            </div>
          </FormItem>
          <div class="flex">
            <Icon type="ios-alert" size="20" style="margin-right: 5px;" color="orange"/>
            菜单修改需刷新页面或重新登录后生效
          </div>
        </Form>
        <Spin size="large" fix v-if="loading"></Spin>
      </cus-modal>
    </div>
  </template>
  
  <script>
  import { getRoleInfo, saveForUnit, modifyForUnit, getRolePermission, modifyRolePermission } from '@/api/organ/system'
  import { getUnitLevelList } from '@/api/organ/dropDown'
  import roleTree from './roleTree'
  
  const form = {
    id: '',
    name: '',
    descr: '',
    resourceId: [],
    isAdmin: false, //是否为管理员
    levelCode: '', //单位级别编码
    levelName: '', //单位选项 
    resourceIdList: []
  }
  
  export default {
    components: { roleTree },
    name: 'roleModal',
    data () {
      return {
        loading: false,
        form: form,
        permissionList: [], //菜单权限列表
    permissionIdList: [], //权限id列表
    unitLevelList: [],
        ruleValidate: {
          resourceIdList: [
            {
              required: true,
              validator: (rule, value, callback) => {
                if (!this.form.resourceId.length) {
                  return callback(new Error('权限列表不能为空'))
                } else return callback()
              },
              trigger: 'blur'
            }
          ]
        }
      }
    },

    mounted () {
      this.form = this.$cu.deepClone(form)
    },
    methods: {
      onVisibleChange (v) {
            this.$refs['formValidate'].resetFields()
        if (!v){
          // 解决数据改变roleTree数据不回显
          this.$nextTick(() => {
            this.form = this.$cu.deepClone(form)
        });
         console.log(this.form);
        }
      },
      show () {
        this.loading = false
        this.$refs['modal'].show = true
        this.getUnitLevelListApi()
        console.log(this.form);
        if (this.form.id) {
          console.log(111);
          this.loading = true
          Promise.all([this.getRoleInfoApi()]).then(() => {
            this.getRolePermissionApi()
          })
        }
      },
      onOver (ids) {
        this.form.resourceId = ids
      },
      onOk () {
        this.$refs['roleTree'].getCheckedAndIndeterminateNodes()
        this.$refs['formValidate'].validate(valid => {
          if (valid) {
            this.$nextTick(() => {
              this.loading = true
              if (this.form.id) {
                this.modifyRoleApi()
              } else this.saveForUnitApi()
            })
          }
        })
      },
    // 是否为管理员
    radioChange() {
      this.form.isAdmin = !this.form.isAdmin
    },
          // 选择单位级别
    changeLevel(val) {
      
      this.unitLevelList.forEach(item => {
        if(item.levelName == val) {
          this.form.levelCode = item.levelCode
        } 
      })
  
    },
     // 获取单位级别列表
     getUnitLevelListApi() {
      return new Promise(resolve => {
        getUnitLevelList({}).then(res => {
          if (res.code === 1) {
            this.unitLevelList = res.data
          }
        })
      })
    },
      // 获取角色详情
      getRoleInfoApi () {
        return new Promise(resolve => {
          getRoleInfo({ id: this.form.id }).then(res => {
            if (res.code === 1) {
              res.data.resourceIdList = []
              this.form = res.data
              this.form.isAdmin =  this.form.isAdmin == 1 ? true : false
              this.form.levelName = res.data.unitLevelName
             
              resolve()
            }
          })
        })
      },
      getRolePermissionApi () {
        return new Promise(resolve => {
          getRolePermission({ roleId: this.form.id }).then(res => {
            if (res.code === 1) {
             
              this.form.resourceIdList = res.data
              resolve()
            }
          })
        })
      },
      // 添加角色接口
      saveForUnitApi () {
        return new Promise(resolve => {
          saveForUnit({
            name: this.form.name,
            isAdmin: this.form.isAdmin ? 1 : 0,
            descr: this.form.descr,
             // 角色单位代码级别
          unitLevelCode: this.form.levelCode,
          }).then(res => {
            if (res.code === 1) {
              this.form.id = res.data
              this.modifyRolePermissionApi().then(() => {
                this.loading = false
                this.$Message.success('添加成功')
                this.$refs['modal'].show = false
                this.$parent.onInit()
              })
              resolve()
            } else this.loading = false
          })
        })
      },
      // 编辑角色接口
      modifyRoleApi () {
        return new Promise(resolve => {
          modifyForUnit({
            id: this.form.id,
            name: this.form.name,
            descr: this.form.descr
          }).then(res => {
            if (res.code === 1) {
              this.modifyRolePermissionApi().then(() => {
                this.loading = false
                this.$Message.success('编辑成功')
                this.$refs['modal'].show = false
  
  
                // 判断是否为当前用户
                if (this.vuex_user.role.filter(v => v.id == this.form.id)) {
                  this.$cu.dialog({title: '提示',content: "修改的为当前用户角色,需要刷新页面才可生效,是否立即刷新"}).then(() => {
                    window.location.reload();
                  })
                }
  
                this.$parent.onInit()
              })
              resolve()
            } else this.loading = false
          })
        })
      },
      // 编辑权限
      modifyRolePermissionApi () {
        return new Promise(resolve => {
          modifyRolePermission({
            roleId: this.form.id,
            resourceIdList: JSON.stringify(this.form.resourceId)
          }).then(res => {
            if (res.code === 1) {
              resolve()
            } else this.loading = false
          })
        })
      }
    }
  }
  </script>
  
  <style scoped lang="less">
    .permission {
      max-height: 400px;
      width: 500px;
      border: 1px solid #dcdee2;
      overflow-y: auto;
      overflow-x: hidden;
      border-radius: 2px;
      padding: 0 0 0 10px;
    }
  // 取消侧边栏
    // .permission::-webkit-scrollbar{
    //   display:none;
    // }
  </style>
  